package com.yj.auto.plugin.log4j;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.log.Log;
import com.yj.auto.core.base.online.SessionUserUtil;

/**
 * Log4j在线查看
 */
public class Log4jServlet extends HttpServlet {

	private static final long serialVersionUID = -260157400324419618L;

	private static final Log log = Log.getLog(Log4jServlet.class);

	@Override
	public void init() throws ServletException {
		super.init();
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	/**
	 * 将客户端注册到监听Logger的消息队列中
	 */
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "no-cache");
		response.setCharacterEncoding("UTF-8");
		if (!SessionUserUtil.isSuperUser(request)) {// 暂时把查看权限给超级用户
			Log4jAsyncWriter.writeJS(response.getWriter(), "<br><b>Sorry, you are not permitted to view this page.</b>");
			return;
		}
		final AsyncContext ac = request.startAsync();
		ac.setTimeout(20 * 60 * 1000);// 20分钟
		ac.addListener(new AsyncListener() {
			public void onComplete(AsyncEvent event) throws IOException {
				Log4jAsyncWriter.removeAsyncContext(ac);
				log.debug("AsyncListener onComplete");
			}

			public void onTimeout(AsyncEvent event) throws IOException {
				Log4jAsyncWriter.removeAsyncContext(ac);
				log.debug("AsyncListener onTimeout", event.getThrowable());
			}

			public void onError(AsyncEvent event) throws IOException {
				Log4jAsyncWriter.removeAsyncContext(ac);
				log.error("AsyncListener onError", event.getThrowable());
			}

			public void onStartAsync(AsyncEvent event) throws IOException {
				log.debug("AsyncListener onStartAsync");
			}
		});
		Log4jAsyncWriter.addAsyncContext(ac);
	}
}
